package com.yunban.project.api.text_check.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.api.text_check.domain.CorrectTaskDetails;
import com.yunban.project.api.text_check.enums.CorrectState;
import com.yunban.project.api.text_check.mapper.CorrectTaskDetailsMapper;
import com.yunban.project.api.text_check.service.CorrectTaskDetailsService;
import com.yunban.project.api.text_check.utils.CorrectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lijiajun
 * @date: 2024-12-04
 * @version: 1.0
 */
@Slf4j
@Service
public class CorrectTaskDetailsServiceImpl extends ServiceImpl<CorrectTaskDetailsMapper, CorrectTaskDetails> implements CorrectTaskDetailsService {
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void batchSaveTask(String taskId, List<CorrectUtils.TextSegment> segments) {
        List<CorrectTaskDetails> detailsList = new ArrayList<>();
        for (CorrectUtils.TextSegment segment : segments) {
            CorrectTaskDetails details = new CorrectTaskDetails();
            details.setTaskId(taskId);
            details.setSort(segment.getIndex());
            // 将\n替换为 \\n
            // 判断 getText 是否有 \n
            if (segment.getText().contains("\n")) {
                // 将 \n转为<br/>
                details.setSentence(segment.getText().replace("\n\n", "<br/>"));
            } else {
                details.setSentence(segment.getText());
            }
            log.info("save task details: {}", details.getSentence());
            details.setStartIndex(segment.getStartIndex());
            details.setEndIndex(segment.getEndIndex());
            detailsList.add(details);
        }
        log.info("save task details: {}", detailsList);
        this.saveBatch(detailsList);
    }

    @Override
    public CorrectTaskDetails getUnParsedTask() {
        // 根据任务ID查询未解析的数据，只能有一条，按照顺序解析 sort
        LambdaQueryWrapper<CorrectTaskDetails> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CorrectTaskDetails::getTaskId, taskId);
        queryWrapper.eq(CorrectTaskDetails::getState, CorrectState.UNKNOWN);
        // 按照两个字段进行排序，createdAt、sort
        queryWrapper.orderByAsc(CorrectTaskDetails::getCreatedAt).orderByAsc(CorrectTaskDetails::getSort);
        // 获取第一条
        CorrectTaskDetails taskDetails = this.getOne(queryWrapper, false);
        // 判断是否存在
        if (ObjectUtils.isEmpty(taskDetails)) {
            return null;
        }
        // 需要修改这条记录的状态，锁住
        taskDetails.setState(CorrectState.PROCESSING);
        if (!this.updateById(taskDetails)) {
            return null;
        }
        return taskDetails;
    }

    @Override
    public List<CorrectTaskDetails> findByTaskIdAndState(String taskId, CorrectState state) {
        LambdaQueryWrapper<CorrectTaskDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CorrectTaskDetails::getTaskId, taskId);
        queryWrapper.eq(CorrectTaskDetails::getState, state);
        // 根据sort进行asc排序
        queryWrapper.orderByAsc(CorrectTaskDetails::getSort);
        return this.list(queryWrapper);
    }

    @Override
    public Boolean checkTaskFinished(String taskId) {
        // 通过taskId获取当前正在进行与未进行的纠错任务
        LambdaQueryWrapper<CorrectTaskDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CorrectTaskDetails::getTaskId, taskId);
        queryWrapper.in(CorrectTaskDetails::getState, CorrectState.PROCESSING, CorrectState.UNKNOWN);
        return this.count(queryWrapper) == 0;
    }

    @Override
    public long countByFinishedAndTaskId(String taskId) {
        LambdaQueryWrapper<CorrectTaskDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CorrectTaskDetails::getState, CorrectState.SUCCESS);
        queryWrapper.eq(CorrectTaskDetails::getTaskId, taskId);
        queryWrapper.ne(CorrectTaskDetails::getSentence, "<br/>");
        return this.count(queryWrapper);
    }
}
